package com.shop.util;

import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 基础工具类
 */
public class BaseUtil {

    //特征码
    public static String Feature_Code = "1a2b3c4d";

    /**
     * MD5加密，32位
     * @return
     */
    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++){
            byteArray[i] = (byte) charArray[i];
        }

        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    /**
     * 加密算法（可逆）
     * @return
     */
    public static String encryptData (String inStr) {
        // String s = new String(inStr);
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    /**
     * 解密算法
     * @return
     */
    public static String decodeData (String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }

    /**
     * 加密用户密码
     * @return
     */
    public static String encryptPw(String userId,String password){
        if(StringUtils.isEmpty(userId)){
            return "noUser";
        }
        if(StringUtils.isEmpty(password)){
            return "noPassword";
        }

        String md5UserId = MD5(userId);
        String md5Password = MD5(password);
        String newPw = md5UserId+"&"+md5Password;   //生成新的字符串进行存储

        return newPw;
    }

    /**
     * 校验密码是否正确
     * @return
     */
    public static boolean isPassValid(String password,String reServePass){
        boolean isPass = false;
        if(StringUtils.isEmpty(password)){
            return false;
        }

        String md5Password = MD5(password);
        String rePassword = reServePass.split(",")[1];
        if(md5Password.equals(rePassword)){
            isPass = true;
        }

        return isPass;
    }


    /**
     * 获取唯一主键字符串
     * @return
     */
    public static synchronized String getSID(){
            return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * JSON转为Map
     *
     * @param json
     * @return Map<String,Object>
     * @exception
     * @since 1.0.0
     */
    public static Map<String, Object> json2Map(String json) {
        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(json);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Iterator<String> its = jsonObject.keys();
        while (its.hasNext()) {
            String key = its.next();
            Object val = jsonObject.get(key);
            dataMap.put(key, val);
        }
        return dataMap;
    }

    /**
     * 字符串数据转码
     * 支持- GB2312 \ ISO-8859-1 \ UTF-8 \ GBK
     *
     */
    public static String dataTranscoding(String str) throws UnsupportedEncodingException {
        String encoding = BaseUtil.getEncoding(str);
        if(BaseUtil.isNotBlank(str) && BaseUtil.isMessyCode(str)){
            //中文乱码问题
            if(encoding.equals("ISO-8859-1")) str =  new String(str.getBytes(encoding),"UTF-8");
            else str =  new String(str.getBytes(encoding),encoding);
        }
        return str;
    }

    /*获取字符串编码格式*/
    public static String getEncoding(String str) {
        String encode = "GB2312";
        try {
            //判断是不是GB2312
            if (str.equals(new String(str.getBytes(encode), encode)))  return encode;  //是的话，返回“GB2312“，以下代码同理
            //判断是不是ISO-8859-1
            encode = "ISO-8859-1";
            if (str.equals(new String(str.getBytes(encode), encode)))  return encode;
            //判断是不是UTF-8
            encode = "UTF-8";
            if (str.equals(new String(str.getBytes(encode), encode)))  return encode;
            //判断是不是GBK
            encode = "GBK";
            if (str.equals(new String(str.getBytes(encode), encode)))  return encode;
        }catch (Exception exception) {
        }
        return ""; //如果都不是，说明输入的内容不属于常见的编码格式。
    }

    /**
     * 对象转JSON
     *
     * @param obj
     * @return String
     * @exception
     * @since 1.0.0
     */
    public static String toJson(Object obj) {
        JSONObject jsonObj = JSONObject.fromObject(obj);
        return jsonObj.toString();
    }

    public static String getString(JSONObject obj, String property) {
        Object item = obj.get(property);
        if (item == null || item instanceof JSONNull) {
            return "";
        } else if ("null".equals(item.toString())) {
            return "";
        } else {
            return item.toString();
        }
    }

    /**
     * 不为空
     *
     * @param obj
     * @return
     */
    public static Boolean isNotBlank(Object obj) {
        return !BaseUtil.isBlank(obj);
    }

    /**
     * 为空
     *
     * @param obj
     * @return
     */
    public static Boolean isBlank(Object obj) {
        String str = null;
        // Integer i = null;
        if (obj == null) {
            return true;
        } else {
            if (obj instanceof String) {
                str = (String) obj;
            } else {
                // ("非String类型");
                // BaseAssert.notNull(null, "非String类型");
                // return true;
                return false;
            }
        }
        Boolean isBlank = StringUtils.isBlank(str);
        if (isBlank) {
            return true;
        }
        // if (str.equalsIgnoreCase("null")) {
        if ("null".equalsIgnoreCase(str)) {
            return true;
        }
        return false;
    }
    /**
     * 检测是否乱码
     * @param strName 字符串
     * @return true/false
     */
    public static boolean isMessyCode(String strName) {
        try {
            Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
            Matcher m = p.matcher(strName);
            String after = m.replaceAll("");
            String temp = after.replaceAll("\\p{P}", "");
            char[] ch = temp.trim().toCharArray();

            int length = (ch != null) ? ch.length : 0;
            for (int i = 0; i < length; i++) {
                char c = ch[i];
                if (!Character.isLetterOrDigit(c)) {
                    String str = "" + ch[i];
                    if (!str.matches("[\u4e00-\u9fa5]+")) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }




}


